﻿using System;
using System.Threading;

namespace VocabUtils
{
	public class DelayedJobRunner
	{
		public int DelayMs = 500;
		Action nextJob;
		private Action runningJob;
		Thread thread;

		object syncObj = new object();

		public bool NextJobWaiting { get { return nextJob != null; } }

		public void RunJob( Action job )
		{
			lock( syncObj )
			{
				this.nextJob = job;

				if( thread != null )
					return;

				thread = new Thread( ThreadMethod ) { IsBackground = true };
				thread.Start();
			}
		}

		private void ThreadMethod()
		{
			Thread.Sleep( DelayMs );
			while( nextJob != null )
			{
				runningJob = nextJob;
				nextJob = null;
				runningJob();
				//try { currentJob(); } catch { }
			}
			thread = null;
		}
	}
}
